import { InfoCircleOutlined } from '@ant-design/icons';
import { Form, Input, InputNumber, Modal, Radio, TreeSelect } from 'antd';
import { useImperativeHandle, useState } from 'react';

import menusApi from '@/api/menusApi';
import { message } from '@/components/AntdGlobal';
import { IMenu } from '@/types/api';
import { IAction, IModalProp } from '@/types/modal';

const CreateMenu = (props: IModalProp<IMenu.EditParams | { parentId?: string; orderBy?: number }>) => {
    /* 数据管理 ---------------------------------------------------*/
    const [visible, setVisible] = useState(false);
    const [action, setAction] = useState<IAction>('create');
    const [form] = Form.useForm();
    const [menuList, setMenuList] = useState<IMenu.MenuItem[]>([]);
    useImperativeHandle(props.mRef, () => {
        return {
            openModal
        };
    }); // 暴露子组件open方法，供父组件中直接调用子组件引用ref的方法

    /* 函数定义 ---------------------------------------------------*/
    /**弹框显示
     * @param action 类型
     * @param data 数据
     */
    const openModal = (action: IAction, data?: IMenu.EditParams | { parentId?: string; orderBy?: number }) => {
        setAction(action);
        setVisible(true);
        // 数据时效性，每次打开弹窗时重新获取数据
        getMenusList();
        // 新增 or 编辑，表单赋值
        if (data && (action === 'create' || action === 'edit')) {
            form.setFieldsValue({ ...data });
        }
    };

    /**获取菜单列表
     */
    const getMenusList = async () => {
        const { data } = await menusApi.getMenusList();
        setMenuList(data);
    };

    /**提交操作
     */
    const handleSubmit = async () => {
        try {
            const valid = await form.validateFields();
            if (valid) {
                const values = form.getFieldsValue();
                if (action === 'create') {
                    await menusApi.createMenu(values);
                    message.success('创建成功');
                } else {
                    await menusApi.editMenu(values);
                    message.success('修改成功');
                }
            }
            // 关闭弹窗，重置表单数据
            handleCancel();
            // 父组件更新列表
            props.update();
        } catch (error) {
            console.error(error);
        }
    };

    /**取消操作
     */
    const handleCancel = () => {
        setVisible(false);
        form.resetFields();
    };
    return (
        <Modal
            title={action === 'create' ? '创建菜单' : '编辑菜单'}
            width={800}
            open={visible}
            okText="确定"
            cancelText="取消"
            onOk={handleSubmit}
            onCancel={handleCancel}
        >
            <Form
                form={form}
                labelAlign="right"
                labelCol={{ span: 4 }}
                initialValues={{ menuType: '1', menuState: '1' }}
            >
                <Form.Item
                    hidden
                    name="menuId"
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="父级菜单"
                    name="parentId"
                >
                    <TreeSelect
                        placeholder="请选择父级菜单"
                        allowClear
                        treeDefaultExpandAll
                        fieldNames={{ label: 'menuName', value: 'menuId' }}
                        treeData={menuList}
                    />
                </Form.Item>
                <Form.Item
                    label="菜单类型"
                    name="menuType"
                >
                    <Radio.Group>
                        <Radio value="1">菜单</Radio>
                        <Radio value="2">按钮</Radio>
                        <Radio value="3">页面</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item
                    label="菜单名称"
                    name="menuName"
                    rules={[{ required: true, message: '请输入菜单名称' }]}
                >
                    <Input placeholder="请输入菜单名称" />
                </Form.Item>
                {/* 动态自定义渲染 */}
                <Form.Item
                    noStyle
                    shouldUpdate
                >
                    {() => {
                        return form.getFieldValue('menuType') === '2' ? (
                            <Form.Item
                                label="权限标识"
                                name="menuCode"
                            >
                                <Input placeholder="请输入权限标识" />
                            </Form.Item>
                        ) : (
                            <>
                                <Form.Item
                                    label="菜单图标"
                                    name="icon"
                                >
                                    <Input placeholder="请输入菜单图标" />
                                </Form.Item>
                                <Form.Item
                                    label="路由地址"
                                    name="path"
                                    tooltip={{
                                        title: '末级菜单必填',
                                        icon: <InfoCircleOutlined />
                                    }}
                                >
                                    <Input placeholder="请输入路由地址" />
                                </Form.Item>
                            </>
                        );
                    }}
                </Form.Item>
                <Form.Item
                    label="排序"
                    name="orderBy"
                    tooltip={{
                        title: '排序值越大越靠后',
                        icon: <InfoCircleOutlined />
                    }}
                >
                    <InputNumber placeholder="请输入排序值" />
                </Form.Item>
                <Form.Item
                    label="菜单状态"
                    name="menuState"
                >
                    <Radio.Group>
                        <Radio value="1">启用</Radio>
                        <Radio value="2">停用</Radio>
                    </Radio.Group>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default CreateMenu;
